package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {


    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    @Lazy
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 自媒体文章自动审核
     * @param id
     */
    @Async("taskExecutor")  //标明当前方法是一个被异步调用的方法
//    @GlobalTransactional
    @Override
    public void autoScanWmNews(Integer id) {

        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(null == wmNews){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-自媒体文章不存在");
        }

        //文章必须是状态为1的时候，才能审核
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){

            //提取文章中的纯文本和图片的url
            Map<String,Object> textAndImageMap = handleTextAndImages(wmNews);

            //自管理敏感词审核
            boolean isSensitive = handleSensitive((String) textAndImageMap.get("content"),wmNews);
            if(!isSensitive)return;

            //2.审核文章的文本内容
            boolean isTextScan = handleTextScan((String) textAndImageMap.get("content"),wmNews);
            if(!isTextScan)return;

            //3.审核文章的图片
            boolean isImageScan = handleImageScan((List<String>) textAndImageMap.get("images"),wmNews);
            if(!isImageScan)return;

            //判断是否到发布时间
            if(wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                //添加到延迟队列中，等待发布
                wmNewsTaskService.addWmNewsToTask(wmNews);
                return;
            }

            //发布文章
            pubishNews(wmNews);
        }

    }

    /**
     * 发布文章
     * @param wmNews
     */
    public void pubishNews(WmNews wmNews) {
        //4.保存app端的相关文章（feign远程调用）
        ResponseResult responseResult = saveAppArticle(wmNews);
        if(responseResult == null || !responseResult.getCode().equals(200)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-article端保存数据失败");
        }

        //int i = 1 / 0;

        //5.修改wm_news中的article_id这个字段，状态改为9（已发布）
        wmNews.setArticleId((Long) responseResult.getData());
        updateWmNews(wmNews,WmNews.Status.PUBLISHED.getCode(),"文章已发布");

        //发送消息，生成文章的详情页面，参数就是：article_id
        Map<String,Object> map = new HashMap<>();
        map.put("article_id", wmNews.getArticleId());

        kafkaTemplate.send(WmNewsMessageConstants.ARTICLE_STATIC_URL_CREATE_TOPIC,JSON.toJSONString(map));
    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {


        //初始化敏感词库  select * from wm_sensitive  ---> select sensitives from wm_sensitive
        List<WmSensitive> wmSensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        //数据转换
        List<String> sensitiveStrList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        SensitiveWordUtil.initMap(sensitiveStrList);

        //匹配内容是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content + "_" + wmNews.getTitle());
        if(map.size() > 0){
            //修改文章
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(), "文章中包含了敏感词，敏感词为="+map);
            return  false;
        }
        return true;
    }


    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    /**
     * 保存app端的相关文章（feign远程调用）
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        /*ArticleDto dto = new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);

        //布局
        dto.setLayout(wmNews.getType());
        //创建时间
        dto.setCreatedTime(new Date());
        dto.setLikes(0);
        dto.setComment(0);
        dto.setCollection(0);
        dto.setViews(0);


        //当这个文章之前审核通过 过，意味着当前自媒体文章表中就有article_id（有值）
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }

        //填充作者信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(null != wmUser){
            dto.setAuthorId(wmUser.getId().longValue());
            dto.setAuthorName(wmUser.getName());
        }
        //构建频道数据
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(null != wmChannel){
            dto.setChannelName(wmChannel.getName());
        }*/

        ArticleDtoBuilder articleDtoBuilder = new ArticleDtoBuilder(wmNews,wmUserMapper,wmChannelMapper);

        ArticleDto dto = articleDtoBuilder
                .buildBeanCopy()
                .buildBasic()
                .buildAuthor()
                .buildChannel()
                .builder();

        ResponseResult responseResult = articleClient.saveAppArticle(dto);
        return responseResult;

    }


    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核文章的图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        if(images == null || images.size() ==0){
            return flag;
        }

        //把图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();


        //调用阿里云接口审核图片
        try {

            for (String url : images) {
                //下载图片
                byte[] bytes = fileStorageService.downLoadFile(url);
                imageList.add(bytes);

                //集成图片识别文字，审核（自管理的敏感词审核）
                /*ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                String resultStr = tess4jClient.doOCR(bufferedImage);
                //审核识别之后的文本内容
                boolean isSensitive = handleSensitive(resultStr, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }*/
            }

            Map map = greenImageScan.imageScan(imageList);
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中存在违规内容");
                    flag = false;
                }

                //人工审核
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中存在不确定内容");
                    flag = false;
                }
            }

        } catch (Exception e) {
            flag = false;
        }

        return flag;

    }

    /**
     * 文本审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        try {
            Map map = greenTextScan.greeTextScan(content + "_" + wmNews.getTitle());
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中存在违规内容");
                    flag = false;
                }

                //人工审核
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中存在不确定内容");
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;


    }

    /**
     * 修改文章
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, Short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 取文章中的纯文本和图片的url
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        Map<String, Object> resultMap = new HashMap<>();

        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        //从文章的内容中解析数据
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            //纯文本
            if(map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }

            //图片
            if(map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }
        }

        //封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);


        return resultMap;
    }
}
